# -*- coding: utf-8 -*-
from billing.models import Consumption ,Price ,HourRecord
from register.keystone_util import Keystone
from register.ceilometer_util import Ceilometer
import time
import datetime
import decimal
from decimal import Decimal
import logging
log=logging.getLogger('django')

def generate_hours_consumption():
    
    now = datetime.datetime.now()
    endTime = now + datetime.timedelta(hours=-1)
    print now
    print endTime
    print "----时定时任务开始----"
    try:
        cclient = Ceilometer()
        c_client = cclient.client()
        
        keystoneclient = Keystone()
        v_client = keystoneclient.admin_login()
        
        tenantlist = keystoneclient.get_tenant_list(v_client)
    except:
        print "客户端获取异常"
    try:
        memoryPrice = Price.objects.filter(price_name='内存').filter(status=0)[0].unit_price
        diskPrice = Price.objects.filter(price_name='磁盘').filter(status=0)[0].unit_price
        cpuPrice = Price.objects.filter(price_name='vcpu').filter(status=0)[0].unit_price
    except:
        memoryPrice = Decimal(0)
        diskPrice = Decimal(0)
        cpuPrice = Decimal(0)
    
    for item in tenantlist:
        project_id = item.id
        print project_id
        try:
            temp = cclient.getHourUseDataByProject(c_client,60*60,endTime,project_id)
            print temp
            cpu_consume = Decimal(Decimal(temp[u'cpu_use']) * Decimal(cpuPrice)).quantize(Decimal('0.00'))
            disk_consume = Decimal(Decimal(temp[u'disk_use']) * Decimal(diskPrice)).quantize(Decimal('0.00'))
            memory_consume = Decimal(Decimal(temp[u'memory_use']) * Decimal(memoryPrice)).quantize(Decimal('0.00'))
            print cpu_consume
        except:
            print "数据异常"
        try:
            hrecord = HourRecord(project_id=project_id,cpu_use=temp[u'cpu_use'],memory_use=temp[u'memory_use'],disk_use=temp[u'disk_use']
                                 ,cpu_price=cpuPrice,disk_price=diskPrice,memory_price=memoryPrice,cpu_unit=temp[u'cpu_unit'],disk_unit=temp[u'disk_unit'],memory_unit=temp[u'memory_unit']
                                 ,cpu_consume=cpu_consume,disk_consume=disk_consume,memory_consume=memory_consume)
            hrecord.save()
        except:
            print "数据保存异常"
    else:
        print datetime.datetime.now()
        print "----时定时任务结束----"